#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include <functional>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include "nocopy.hpp"
#include "Log.hpp"
#include "Epoller.hpp"
#include "Socket.hpp"
#include "Comm.hpp"

class Connection;
class TcpServer;

uint32_t EVENT_IN = (EPOLLIN | EPOLLET);
uint32_t EVENT_OUT = (EPOLLOUT | EPOLLET);
static const int g_buffer_size = 1024;

using func_t = std::function<void(std::shared_ptr<Connection>)>;
using except_func = std::function<void(std::weak_ptr<Connection>)>;

class Connection : nocopy
{
public:
    Connection(int sock, std::shared_ptr<TcpServer> tcp_server_ptr)
        : _sock(sock),
          _tcp_server_ptr(tcp_server_ptr)
    {
    }
    void SetHandler(func_t recv_cb, func_t send_cb, func_t except_cb)
    {
        _recv_cb = recv_cb;
        _send_cb = send_cb;
        _except_cb = except_cb;
    }
    int SockFd() { return _sock; }
    void Append(const std::string &str)
    {
        _inbuffer += str;
    }
    std::string &Inbuffer() { return _inbuffer; }
    ~Connection()
    {
    }

private:
    int _sock;
    std::string _inbuffer; // string不能处理二进制流,vector更合适,但是要我们自己写缓冲区,比较麻烦,先用string
    std::string _outbuffer;

public:
    func_t _recv_cb;
    func_t _send_cb;
    func_t _except_cb;
    std::string _ip;
    uint16_t _port;

    // 添加一个回指指针
    std::shared_ptr<TcpServer> _tcp_server_ptr;
    // std::weak_ptr<TcpServer> _tcp_server_ptr;
};
class TcpServer
{
    static const int num = 64;

public:
    TcpServer(uint16_t port, func_t OnMessage)
        : _port(port),
          _OnMessage(OnMessage),
          _quit(false),
          _epoller_ptr(new Epoller()),
          _listensock_ptr(new Sock())
    {
    }
    void Init()
    {
        _listensock_ptr->Socket();
        SetNonBlockOrDie(_listensock_ptr->Fd());
        _listensock_ptr->Bind(_port);
        _listensock_ptr->Listen();
        lg(Info, "create listen socket success: %d", _listensock_ptr->Fd());
        AddConnection(_listensock_ptr->Fd(), EVENT_IN,
                      std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);
    }
    void AddConnection(int sock, uint32_t event, func_t recv_cb, func_t send_cb, func_t except_cb,
                       std::string ip = "0.0.0.0", uint16_t port = 0)
    {
        // 1. 给sock建立一个connection对象,将listensock添加到Connection中,同时,listensock和Connection放入_connections
        std::shared_ptr<Connection> new_connect = std::make_shared<Connection>(sock,
                                                                               std::shared_ptr<TcpServer>(this));
        new_connect->SetHandler(recv_cb, send_cb, except_cb);
        new_connect->_ip = ip;
        new_connect->_port = port;
        // 2. 添加到unordered_map
        _connections.insert(std::make_pair(sock, new_connect));
        // 3. 我们添加对应的事件，还要添加到内核中
        _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, sock, event);
        lg(Debug, "add a new connection success, sockfd is: %d", sock);
    }
    // 链接管理器
    void Accepter(std::shared_ptr<Connection> connection)
    {
        while (true)
        {
            struct sockaddr_in peer; // 存客户端的连接
            socklen_t len = sizeof(peer);
            int sock = ::accept(connection->SockFd(), (struct sockaddr *)&peer, &len);
            if (sock > 0)
            {
                uint16_t peerport = ntohs(peer.sin_port);
                char ipbuf[1024];
                inet_ntop(AF_INET, &peer.sin_addr.s_addr, ipbuf, sizeof(ipbuf));
                lg(Debug, "get a new client, get info-> [%s:%d], sockfd: %d", ipbuf, peerport, sock);

                SetNonBlockOrDie(sock);
                // listensock只需要设置
                AddConnection(sock, EVENT_IN,
                              std::bind(&TcpServer::Recver, this, std::placeholders::_1),
                              std::bind(&TcpServer::Sender, this, std::placeholders::_1),
                              std::bind(&TcpServer::Except, this, std::placeholders::_1));
            }
            else
            {
                if (errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                    break;
            }
        }
    }
    // 事件管理器
    // 应不应该关心数据的格式？不应该！服务器只要IO数据就可以，有没有读完，报文的格式细节，你不用管, 上层处理。
    void Recver(std::shared_ptr<Connection> connection)
    {
        // std::cout << "haha, got you!!!, sockfd: " << connection->SockFd() << std::endl;
        int sock = connection->SockFd();
        while (true)
        {
            char buffer[g_buffer_size];
            memset(buffer, 0, sizeof(buffer));
            ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0 /*阻塞*/); // 之前我们已经设为了非阻塞
            if (n > 0)
            {
                connection->Append(buffer);
            }
            else if (n == 0)
            {
                lg(Info, "sockfd: %d, client info %s:%d quit...", sock,
                   connection->_ip.c_str(), connection->_port);
                connection->_except_cb(connection);
            }
            else
            {
                if (errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    lg(Warning, "sockfd: %d, client info %s:%d quit...", sock,
                       connection->_ip.c_str(), connection->_port);
                    connection->_except_cb(connection);
                    return;
                }
            }
        }
        // 数据有了，但是不一定全，需要做：1. 检测 2. 如果有完整报文，就处理
        _OnMessage(connection);
    }
    void Sender(std::shared_ptr<Connection> connection)
    {
    }
    void Except(std::shared_ptr<Connection> connection)
    {
        lg(Warning, "Excepter hander sockfd: %d, client info %s:%d quit...", connection->SockFd(),
           connection->_ip.c_str(), connection->_port);
    }
    bool IsConnectionSafe(int fd)
    {
        auto it = _connections.find(fd);
        if (it != _connections.end())
            return true;
        else
            return false;
    }
    void Dispatcher(int timeout)
    {
        int n = _epoller_ptr->EpollerWait(revs, num, timeout);
        for (int i = 0; i < n; i++)
        {
            uint32_t events = revs[i].events;
            int sock = revs[i].data.fd;
            // 统一把事件异常转换为读写问题
            if (events & EPOLLERR)
                events |= (EPOLLIN | EPOLLOUT);
            if (events & EPOLLHUP)
                events |= (EPOLLIN | EPOLLOUT);
            // 只需要处理 EPOLLIN / EPOLLOUT
            if ((events & EPOLLIN) && IsConnectionSafe(sock))
            {
                if (_connections[sock]->_recv_cb)
                    _connections[sock]->_recv_cb(_connections[sock]);
            }
            if ((events & EPOLLOUT) && IsConnectionSafe(sock))
            {
                if (_connections[sock]->_send_cb)
                    _connections[sock]->_send_cb(_connections[sock]);
            }
        }
    }
    void Loop()
    {
        _quit = false;

        // AddConnection();

        while (!_quit)
        {
            Dispatcher(3000);
            PrintConnection();
        }

        _quit = true;
    }
    void PrintConnection()
    {
        std::cout << "_connections fd list: ";
        for (auto &connection : _connections)
        {
            std::cout << connection.second->SockFd() << "  ";
            std::cout << "inbuffer: " << connection.second->Inbuffer();
        }
        std::cout << std::endl;
    }
    ~TcpServer()
    {
    }

private:
    std::shared_ptr<Epoller> _epoller_ptr; // 内核
    std::shared_ptr<Sock> _listensock_ptr; // 监听socket, 可以把他移除到外面
    std::unordered_map<int, std::shared_ptr<Connection>> _connections;
    struct epoll_event revs[num];
    uint16_t _port;
    bool _quit;

    // 让上层处理信息
    func_t _OnMessage;
};